package com.lagou.edu.servlet;

import com.lagou.edu.dao.AccountDao;
import com.lagou.edu.factory.AnnoBeanFactory;
import com.lagou.edu.pojo.Account;
import com.lagou.edu.pojo.Result;
import com.lagou.edu.service.TransferService;
import com.lagou.edu.utils.ConnectionUtils;
import com.lagou.edu.utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author 应癫
 */
@WebServlet(name="HelloServlet",urlPatterns = "/helloServlet")
public class HelloServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter writer = resp.getWriter();
        try {
            writer.println("Hey I am from servlet, are you okey? " + getName());
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        PrintWriter writer = resp.getWriter();
//        writer.println("Hey I am from servlet");
//        req.setAttribute("username","java");
//        req.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(req,resp);
    }

    protected String getName() throws Exception {
        ConnectionUtils connectionUtils = new ConnectionUtils();
        Connection con = connectionUtils.getCurrentThreadConn();
        String sql = "select * from lg_users where id=?";
        PreparedStatement preparedStatement = con.prepareStatement(sql);
        preparedStatement.setString(1, "1");
        ResultSet resultSet = preparedStatement.executeQuery();

        int i = 0;
        String name = null;
        while(resultSet.next()) {
            if (i > 1) break;
            name = resultSet.getString("name");
        }

        resultSet.close();
        preparedStatement.close();
        //con.close();

        return name;
    }
}
